// import { promise } from "uview-plus/libs/function/test";
const baseUrl = 'http://localhost:8081';
// const AU_Token = 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMTExIiwibG9naW5fdXNlcl9rZXkiOiI5NzkzYzEyNi0zNTY0LTQ2NTgtYjUyNi0zMTc5ZGZhYjZmMDUifQ.KtIzBWirjfiyQF7P8fKEIU2e11pFGunDCRTOuR-pLQ61aF5q3rP9CcizXg9xiHr_IA8-Gccf_8EyCM5EfoAslQ';
import { request } from "../http";
const createStreamRequest = (question,conversation_id='') => {
  let buffer = '';
  console.log(question)
  const requestTask =uni.request({
    url: `${baseUrl}/v1/chatMessages`,
    method: "POST",
    header: {
      'Authorization': uni.getStorageSync('token') || '',
      'Accept': 'text/event-stream',
    },
    data: {
      inputs: {},
      query: question,
      response_mode: "streaming",
      conversationTitle:'',
      auto_generate_conversation_name: true,
       ...(conversation_id ? { conversation_id } : {}) // 非空时添加 conversation_id
    },
    enableChunked: true,
    responseType: 'text', 
    
    success: (res) => {
    },
    
    fail: (err) => {
      console.error('连接失败:', err);
    },
    
    complete: () => {
    }
  });

  requestTask.onChunkReceived((res) => {
    if (!res.data) return;
    try {
      // 解码数据块
      const chunk = typeof res.data === 'string' ? res.data : new TextDecoder().decode(res.data);
      buffer += chunk;
      while (true) {
        // SSE消息格式: "data: {...}\n\n"
        const dataPrefixIndex = buffer.indexOf('data:');
        if (dataPrefixIndex === -1) break; // 没有完整消息
        
        const endOfMessageIndex = buffer.indexOf('\n\n', dataPrefixIndex);
        if (endOfMessageIndex === -1) break; // 消息不完整
        
        // 提取完整消息
        const message = buffer.substring(dataPrefixIndex, endOfMessageIndex + 2);
        buffer = buffer.substring(endOfMessageIndex + 2); // 移除已处理的消息
        
        // 解析消息内容
        try {
          const jsonStart = message.indexOf('{');
          const jsonEnd = message.lastIndexOf('}') + 1;
          if (jsonStart === -1 || jsonEnd === 0) continue;
          
          const jsonStr = message.substring(jsonStart, jsonEnd);
          const data = JSON.parse(jsonStr);
          // 根据事件类型分发
          if (data.event === 'message') {
            uni.$emit('stream-continue',{
              conversation_id:data.conversation_id||''
            })
            uni.$emit('stream-message', {
              type: 'message',
              data: {
                text: data.answer,
                meta: {
                  message_id: data.message_id
                }
              }
            });
          } else if (data.event === 'message_end') {
            uni.$emit('stream-end', {
              type:'stream_end',
              task_id: data.task_id
            });
          } else if (data.event === 'error') {
            uni.$emit('stream-error', {
              type: 'stream_error',
              error: data.message || '服务器错误'
            });
          }else{
            continue;
          }
        } catch (parseError) {
          console.error('解析SSE消息失败:', parseError, '原始消息:', message);
        }
      }
    } catch (error) {
      console.error('处理分块失败:', error);
      uni.$emit('stream-error', {
        type: 'process_error',
        error: error.message || '处理数据失败'
      });
    }
  });

  return requestTask;
};

export const related = (questionText) =>{
  return request({
      url: '/v1/messageQuery',
      method: 'POST',
      data: {
        inputs: { text: questionText }
      }
    });
  // return new Promise((resolve , reject)=>{
  //   uni.request({
  //     url:`${baseUrl}/v1/messageQuery`,
  //     method:"POST",
  //     header: {
  //       'Authorization':AU_Token
  //     },
  //     data:{
  //       inputs:{
  //         text:questionText
  //       }
  //     },
  //     success: (res) => {
  //       resolve(res.data);
  //     },
  //     fail: (err) => {
  //       reject(err);
  //     }
  //   });
  // });
};
export const relatedPolicy = (question) =>{
  return request({
      url: '/v1/messageTitle',
      method: 'POST',
      data: {
        inputs: { text: question }
      }
    });
  // return new Promise((resolve , reject)=>{
  //   uni.request({
  //     url:`${baseUrl}/v1/messageTitle`,
  //     method:"POST",
  //     header: {
  //       'Authorization':AU_Token
  //     },
  //     data:{
  //       inputs:{
  //         text:question
  //       }
  //     },
  //     success: (res) => {
  //       resolve(res.data);
  //     },
  //     fail: (err) => {
  //       reject(err);
  //     }
  //   });
  // });
};
export const evaluate = (evaluateData)=>{
  return request({
      url: '/v1/evaluateChat',
      method: 'PUT',
      data: evaluateData
    });
  // return new Promise((resolve,reject)=>{
  //   uni.request({
  //     url:`${baseUrl}/v1/evaluateChat`,
  //     method:"PUT",
  //     header:{
  //       'Authorization':AU_Token
  //     },
  //     data:evaluateData,
  //     success: (res) => resolve(res.data),
  //     fail: (err) => reject(err)
  //   })
  // })
}
export const detaile =(policyId)=>{
  return request({
      url: `/wechat/policy/${policyId}`,
      method: 'GET'
    });
  // return new Promise ((resolve ,reject)=>{
  //   uni.request({
  //     url:`${baseUrl}/wechat/policy/${policyId}`,
  //     method:'GET',
  //     header:{
  //       'Authorization':AU_Token
  //     },
  //     success:(res)=>{
  //       resolve(res.data);
  //     },
  //     fail: (err) => {
  //       reject(err);
  //     }
  //   });
  // });
};

export const newPolicy = () => {
  return request({
      url: '/wechat/policy/latest',
      method: 'GET'
    });
  // return new Promise((resolve, reject) => {
  //   uni.request({
  //     url: `${baseUrl}/wechat/policy/latest`, 
  //     method: 'GET',
  //     header: { 'Authorization': AU_Token },
  //     success: (res) => resolve(res.data), 
  //     fail: (err) => reject(err) 
  //   });
  // });
};
export default createStreamRequest;